package com.tjbank.cssys.web.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tjbank.cssys.domain.CkOrderLoanDivisionTimes;
import com.tjbank.cssys.domain.CkOrderLoanIntelligenceDivision;
import com.tjbank.cssys.domain.CkOrderLoanOutsourcing;
import com.tjbank.cssys.domain.CkOrderLoanPeopleDivision;
import com.tjbank.cssys.repository.CkOrderLoanDivisionTimesMapper;
import com.tjbank.cssys.repository.CkOrderLoanIntelligenceDivisionMapper;
import com.tjbank.cssys.repository.CkOrderLoanPeopleDivisionMapper;
import com.tjbank.cssys.web.service.CkOrderLoanIntelligenceDivisionService;
import com.tjbank.cssys.web.service.CkOrderLoanOutsourcingService;
import com.tjbank.cssys.web.util.ReDivisionUtils;
import com.tjbank.cssys.web.util.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CkOrderLoanIntelligenceDivisionServiceImpl implements CkOrderLoanIntelligenceDivisionService {
    protected static final Logger logger = LoggerFactory.getLogger(CkOrderLoanIntelligenceDivisionServiceImpl.class);
    @Autowired
    private CkOrderLoanIntelligenceDivisionMapper ckOrderLoanIntelligenceDivisionMapper;
    @Autowired
    private CkOrderLoanPeopleDivisionMapper ckOrderLoanPeopleDivisionMapper;
    @Autowired
    private ReDivisionUtils reDivisionUtils;
    @Autowired
    private RedisService redisService;
    @Autowired
    private CkOrderLoanOutsourcingService ckOrderLoanOutsourcingService;
    @Autowired
    private CkOrderLoanDivisionTimesMapper ckOrderLoanDivisionTimesMapper;
    @Value("${loginUserName}")
    private String loginUserNameAdmin;
    public PageInfo selectDivisionList(Map<String, String> params, HttpServletRequest request) {
        logger.info("获取分案列表start---参数：param:"+params.toString());
        int page = Integer.parseInt(params.getOrDefault("page", "1").toString());
        int pageSize = Integer.parseInt(params.getOrDefault("pageSize", "10").toString());
        PageHelper.startPage(page, pageSize);
        if(params.get("dataTime")!=null && !"".equals(params.get("dataTime"))){
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
            String dateTime=params.get("dataTime").toString();
            String contentStr1 = dateTime.replaceAll("[\\[\\]]", "");
            String [] dateAr= contentStr1.split(",");
            String beginTime=simpleDateFormat.format(new Date(Long.valueOf(dateAr[0].trim())));
            String endTime=simpleDateFormat.format(new Date(Long.valueOf(dateAr[1].trim())));
            params.put("beginTime",beginTime);
            params.put("endTime",endTime);
        }
        List<CkOrderLoanIntelligenceDivision> list = ckOrderLoanIntelligenceDivisionMapper.selectDivisionList(params);
        PageInfo pageInfo = new PageInfo<>(list);
        logger.info("获取分案列表end---result：pageInfo:"+pageInfo.toString());
        return pageInfo;
    }

    @Override
    public CkOrderLoanIntelligenceDivision getCkOrderLoanDivionById(int id) {
        logger.info("获取分案详情start---参数：id:"+id);
        CkOrderLoanIntelligenceDivision ckOrderLoanIntelligenceDivision =ckOrderLoanIntelligenceDivisionMapper.selectCkOderDivisionById(id);
        logger.info("获取分案详情start---参数：result:"+ JSONObject.toJSONString(ckOrderLoanIntelligenceDivision));
        return ckOrderLoanIntelligenceDivision;
    }

    @Override
    public boolean updateAndToLog(String ids, Byte n_outbound, String model_type,Byte status) throws Exception {
        if (StringUtils.isNotBlank(ids)) {
            String[] split = ids.split(",");
            StringBuilder stringBuilder = new StringBuilder();
            List<CkOrderLoanPeopleDivision> ckOrderLoanPeopleDivisions = new ArrayList<>();
            for (int i = 0; i < split.length; i++) {
                String str = split[i];
                Integer id = Integer.parseInt(str);
                //插入人工分案记录
                CkOrderLoanPeopleDivision peopleDivision = new CkOrderLoanPeopleDivision();
                if (status == 1) {
                    CkOrderLoanDivisionTimes ckOrderLoanDivisionTimes=ckOrderLoanDivisionTimesMapper.selectByPrimaryKey(Long.parseLong(String.valueOf(id)));
                    String serialNumber = ckOrderLoanDivisionTimes.getSerialNumber();
                    CkOrderLoanIntelligenceDivision intelligenceDivision = ckOrderLoanIntelligenceDivisionMapper.selectBySerialNumber(serialNumber);
                    Long id1 = intelligenceDivision.getId();
                    if (i == split.length - 1) {
                        stringBuilder.append(id1);
                        ids=stringBuilder.toString();
                    } else {
                        stringBuilder.append(id1).append(",");
                    }
                    //插入人工分案记录
                    BeanUtils.copyProperties(intelligenceDivision, peopleDivision);
                    peopleDivision.setId(null);
                    peopleDivision.setoOutbound(intelligenceDivision.getOutbound());
                } else  {
                    CkOrderLoanOutsourcing ckOrderLoanOutsourcing=ckOrderLoanOutsourcingService.selectByPrimaryKey(id);
                    BeanUtils.copyProperties(ckOrderLoanOutsourcing, peopleDivision);
                    peopleDivision.setId(null);
                    peopleDivision.setoOutbound(ckOrderLoanOutsourcing.getOutbound());
                }
                peopleDivision.setnOutbound(n_outbound);
                Byte s1 = 0;//0未下发，1已下发
                peopleDivision.setStatus(s1);
                peopleDivision.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                ckOrderLoanPeopleDivisions.add(peopleDivision);

                //更改智能分案的下发渠道
                /*intelligenceDivision.setOutbound(n_outbound);
                ckOrderLoanIntelligenceDivisionMapper.updateByPrimaryKey(intelligenceDivision);*/
            }
            //存储人工分案表
            ckOrderLoanPeopleDivisionMapper.insertForEach(ckOrderLoanPeopleDivisions);
            //存储次数log表
            List<CkOrderLoanDivisionTimes> ckOrderLoanDivisionTimesList = new ArrayList<>();
            ckOrderLoanPeopleDivisions.stream().forEach(ckOrderLoanPeopleDivision -> {
                CkOrderLoanDivisionTimes ckOrderLoanDivisionTimes = new CkOrderLoanDivisionTimes();
                BeanUtils.copyProperties(ckOrderLoanPeopleDivision,ckOrderLoanDivisionTimes);
                ckOrderLoanDivisionTimes.setDivision((byte)1);
                ckOrderLoanDivisionTimes.setDataTime(new Date());
                ckOrderLoanDivisionTimes.setOutbound((byte)3);
                if (ckOrderLoanPeopleDivision.getIsFirstIssue() == 1) {
                    ckOrderLoanDivisionTimes.setIsFirstIssue(1);
                } else if (ckOrderLoanPeopleDivision.getIsFirstIssue() == 0) {
                    ckOrderLoanDivisionTimes.setIsFirstIssue(0);
                }
                ckOrderLoanDivisionTimesList.add(ckOrderLoanDivisionTimes);
            });
            ckOrderLoanDivisionTimesMapper.insertForEach(ckOrderLoanDivisionTimesList);
            if (status == 1) {
                return reDivisionUtils.peopleDivision(ids, model_type, n_outbound);
            } else if (status == 2) {
                return reDivisionUtils.outSourcingDivision(ids, model_type, n_outbound);
            } else {
                return false;
            }
        } else {
            return false;
        }
    }



    /**
     * 获取分案历史数据查询表基础信息数据
     * @param params
     * @return
     */
    @Override
    public PageInfo getDivisionListBasics(Map<String, String> params, HttpServletRequest request) {
        logger.info("获取分案列表start---参数：param:"+params.toString());
        int page = Integer.parseInt(params.getOrDefault("page", "1").toString());
        int pageSize = Integer.parseInt(params.getOrDefault("pageSize", "10").toString());
        PageHelper.startPage(page, pageSize);
        if(params.get("dataTime")!=null && !"".equals(params.get("dataTime"))){
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
            String dateTime=params.get("dataTime").toString();
            String contentStr1 = dateTime.replaceAll("[\\[\\]]", "");
            String [] dateAr= contentStr1.split(",");
            String beginTime=simpleDateFormat.format(new Date(Long.valueOf(dateAr[0].trim())));
            String endTime=simpleDateFormat.format(new Date(Long.valueOf(dateAr[1].trim())));
            params.put("beginTime",beginTime);
            params.put("endTime",endTime);
        }
        List<CkOrderLoanDivisionTimes> list = ckOrderLoanDivisionTimesMapper.findDivisionList(params);
        PageInfo pageInfo = new PageInfo<>(list);
        logger.info("获取分案列表end---result：pageInfo:"+pageInfo.toString());
        return pageInfo;
    }
    /**
     * 获取分案历史数据查询表详情表数据
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> getDivisionListDetails(Map<String, Object> params, HttpServletRequest request) {
        logger.info("获取分案列表start---参数：param:"+params.toString());

        if(params.get("dataTime")!=null && !"".equals(params.get("dataTime"))){
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
            String dateTime=params.get("dataTime").toString();
            String contentStr1 = dateTime.replaceAll("[\\[\\]]", "");
            String [] dateAr= contentStr1.split(",");
            String beginTime=simpleDateFormat.format(new Date(Long.valueOf(dateAr[0].trim())));
            String endTime=simpleDateFormat.format(new Date(Long.valueOf(dateAr[1].trim())));
            params.put("beginTime",beginTime);
            params.put("endTime",endTime);
        }
        List<CkOrderLoanDivisionTimes> list = ckOrderLoanDivisionTimesMapper.getDivisionListDetails(params);
        Map<String, Object> resultMap = new HashMap<>();
        if (list.size() > 0) {
            resultMap.put("info", list.get(0));
            resultMap.put("dataList", list);
        }
        logger.info("获取分案列表end---result：resultMap:" + resultMap.toString());
        return resultMap;
    }

    /**
     * 获取还款基础信息
     * @param params
     * @return
     */
    @Override
    public PageInfo getRecoverBasics(Map<String, String> params, HttpServletRequest request) {
        logger.info("获取还款基础列表start---参数：param:"+params.toString());
        int page = Integer.parseInt(params.getOrDefault("page", "1").toString());
        int pageSize = Integer.parseInt(params.getOrDefault("pageSize", "10").toString());
        PageHelper.startPage(page, pageSize);
        if(params.get("dataTime")!=null && !"".equals(params.get("dataTime"))){
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
            String dateTime=params.get("dataTime").toString();
            String contentStr1 = dateTime.replaceAll("[\\[\\]]", "");
            String [] dateAr= contentStr1.split(",");
            String beginTime=simpleDateFormat.format(new Date(Long.valueOf(dateAr[0].trim())));
            String endTime=simpleDateFormat.format(new Date(Long.valueOf(dateAr[1].trim())));
            params.put("beginTime",beginTime);
            params.put("endTime",endTime);
        }
        List<CkOrderLoanIntelligenceDivision> list = ckOrderLoanIntelligenceDivisionMapper.getRecoverBasics(params);
        PageInfo pageInfo = new PageInfo<>(list);
        logger.info("获取还款基础列表end---result：pageInfo:"+pageInfo.toString());
        return pageInfo;

    }

    /**
     * 还款查询详情
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> getRecoverDetails(Map<String, String> params, HttpServletRequest request) {
        logger.info("获取还款查询详情start---参数：param:"+params.toString());
        if(params.get("dataTime")!=null && !"".equals(params.get("dataTime"))){
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
            String dateTime=params.get("dataTime").toString();
            String contentStr1 = dateTime.replaceAll("[\\[\\]]", "");
            String [] dateAr= contentStr1.split(",");
            String beginTime=simpleDateFormat.format(new Date(Long.valueOf(dateAr[0].trim())));
            String endTime=simpleDateFormat.format(new Date(Long.valueOf(dateAr[1].trim())));
            params.put("beginTime",beginTime);
            params.put("endTime",endTime);
        }
        List<CkOrderLoanIntelligenceDivision> list = ckOrderLoanIntelligenceDivisionMapper.getRecoverDetails(params);
        Map<String, Object> resultMap = new HashMap<>();
        if (list.size() > 0) {
            resultMap.put("info", list.get(0));
            resultMap.put("dataList", list);
        }
        logger.info("获取还款查询详情end---result：resultMap:" + resultMap.toString());
        return resultMap;

    }
}
